package com.server;

import com.config.Config;
import com.handle.RpcRequestHandle;
import com.handle.RpcResponseHandle;
import com.protocol.MessageCodecSharable;
import com.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author linyu.dai
 * @project rpc
 * @description 服务器
 * @creat 2022/11/27 16:04:01
 */
@Slf4j
public class RpcServer {
    private static final Integer PORT = Integer.valueOf(Config.get("rpc.server.port"));
    private static final String SERVER_NAME = Config.get("rpc.application.name");

    public static void run() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Channel channel = new ServerBootstrap()
                    .group(group)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ProtocolFrameDecoder());
                            ch.pipeline().addLast(new MessageCodecSharable());
                            ch.pipeline().addLast(new RpcRequestHandle());
                            ch.pipeline().addLast(new RpcResponseHandle());
                        }
                    }).bind(PORT).sync().channel();
            log.info("{} run success:{}",SERVER_NAME,PORT);
            //监听channel关闭
            channel.closeFuture().addListener(future -> {
                //关闭group线程池 彻底关闭client
                group.shutdownGracefully();
            });
        } catch (Exception e) {
            log.error("register server error {}", e.getMessage());
        }
    }
}
